package com.tg.paw.ums.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.paw.common.util.CommonPageResult;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.common.util.QueryUtil;
import com.tg.paw.ums.params.PermissionButtonsParams;
import com.tg.paw.ums.entity.Permission;
import com.tg.paw.ums.service.IApiPermissionService;
import com.tg.paw.ums.service.IPermissionService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 权限 前端控制器
 * </p>
 *
 * @author Rubble
 * @since 2020-10-22
 */
@RestController
@Slf4j
@Api(tags = "权限管理", value = "PermissionController")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IApiPermissionService apiPermissionService;


    @ApiOperation("根据条件分页查询权限列表")
    @GetMapping(value = "/api/ums/permission")
    public CommonResult getPermissionByPage(Permission entity,
                                    @RequestParam(value = "current", defaultValue = "1") Integer pageNo,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "sorter", defaultValue = "") String sorter,
                                    @RequestParam(value = "filter", defaultValue = "") String filter) {
        try {
            QueryUtil.writeEmptyString2Null(entity);
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>(entity);
            QueryUtil.buildQuery(queryWrapper,filter,sorter,Permission.class);

            if(StringUtils.isEmpty(entity.getPermissionName()) && StringUtils.isEmpty(entity.getAuthority())){
                queryWrapper.eq("parent_id",0L);
            }
            Page<Permission> page = permissionService.page(new Page<>(pageNo, pageSize), queryWrapper);
            if(StringUtils.isEmpty(entity.getPermissionName()) && StringUtils.isEmpty(entity.getAuthority())){
                List<Permission> permissionList = page.getRecords();
                for (Permission permission : permissionList) {
                    permissionService.fetchChildrenTree(permission);
                }
            }

            return CommonPageResult.pageResult(page);
        } catch (Exception e) {
            log.error("根据条件查询所有权限：{}", e.getMessage(), e);
        }
        return CommonResult.failed();
    }

    @ApiOperation("保存权限表")
    @PostMapping(value = "/api/ums/permission")
    public CommonResult savePermission(@RequestBody Permission entity) {
            try {
            if (permissionService.save(entity)) {
                return CommonResult.success();
            }
            } catch (Exception e) {
                log.error("保存权限表：{}", e.getMessage(), e);
                return CommonResult.failed();
            }
            return CommonResult.failed();
    }

    @ApiOperation("更新权限")
    @PutMapping(value = "/api/ums/permission/{id}")
    public CommonResult updatePermission(@RequestBody Permission entity,@ApiParam("权限id") @PathVariable Long id) {

        try {
            entity.setPermissionId(id);
            if (permissionService.updateById(entity)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("更新权限：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("删除权限")
    @DeleteMapping(value = "/api/ums/permission/{id}")
    public CommonResult deletePermission(@ApiParam("权限id") @PathVariable Long id) {
        try {
            if (permissionService.removeById(id)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("删除权限：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("查询权限")
    @GetMapping(value = "/api/ums/permission/{id}")
    public CommonResult getPermissionById(@ApiParam("权限id") @PathVariable Long id) {
        try {
            Permission coupon = permissionService.getById(id);
            return CommonResult.success(coupon);
        } catch (Exception e) {
            log.error("查询权限：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "批量删除权限")
    @DeleteMapping(value = "/api/ums/permission")
    public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean success = permissionService.removeByIds(ids);
        return CommonResult.instance(success);
    }

    /**
     * 只处理枚举内容 PermissionButtonEnum
     * @param params
     * @return
     */
    @ApiOperation(value = "批量更新权限按钮")
    @PostMapping(value = "/api/ums/permission/buttons")
    public CommonResult updatePermissionButtons(@RequestBody PermissionButtonsParams params) {
        return apiPermissionService.updatePermissionButtons(params);
    }

}
